var nums = new Array();
var score = 0;
var hasConflicted = new Array();//是否已叠加，原来解单元格重复叠加的问题

var startx = 0;
var starty = 0;
var endx = 0;
var endy = 0;

$(document).ready(function(){
	newgame();
});

//开始新游戏
function newgame(){
	if(documentwidth>500){
		containerwidth = 500;
		cellwidth = 100; 
		cellspacewidth = 20;
	}else{
		//设置移动端的尺寸
		settingForMobile();
	}
	
	init();
}

function settingForMobile(){
	$('#header .title').css('font-size',cellwidth*0.8);
	$('#header .author').css('font-size',cellwidth*0.3);
	
	$('#header .wrapper').css('width',containerwidth);
	$('#header .score-wrapper,#header .newgame-wrapper').css('width',cellwidth*1.5);
	$('#header .score-wrapper,#header .newgame-wrapper').css('padding',cellwidth*0.06);
	$('#header .score-wrapper,#header .newgame-wrapper').css('border-radius:',cellwidth*0.06);
	$('#header .score-wrapper,#header .newgame-wrapper').css('font-size',cellwidth*0.2);
	$('#header .score-wrapper #score').css('font-size',cellwidth*0.3);

	$('#grid-container').css('width',containerwidth - cellspacewidth*2);
	$('#grid-container').css('height',containerwidth - cellspacewidth*2);
	$('#grid-container').css('padding',cellspacewidth);
	$('#grid-container').css('border-radius',containerwidth*0.02);
	
	$('#grid-container .grid-cell').css('width',cellwidth);
	$('#grid-container .grid-cell').css('height',cellwidth);
	$('#grid-container .grid-cell').css('border-radius',cellwidth*0.1);
	
}

//初始化页面
function init(){
	//初始化单元格的位置(下层)
	for(var i = 0;i < 4;i++){
		for(var j = 0;j < 4;j++){
			var gridCell = $('#grid-cell-'+i+'-'+j);
			gridCell.css('top',getPosTop(i,j));
			gridCell.css('left',getPosLeft(i,j));
		}
	}
	
	//初始化二维数组
	for(var i=0;i<4;i++){
		nums[i] = new Array();
		hasConflicted[i] = new Array();
		for(var j=0;j<4;j++){
			nums[i][j] = 0;
			hasConflicted[i][j] = false;//false表示未曾叠加过，true表示已经叠加过
		}
	}
	
	//在随机的两个单元格生成数字
	generateOneNumber();
	generateOneNumber(); 
	
	
	//动态创建上层单元格并初始化
	updateView();
	score = 0;
	updateScore(score);
}

//更新上层单元格
function updateView(){
	//将上层单元格清空
	$('.number-cell').remove();
	
	for(var i=0;i<4;i++){
		for(var j=0;j<4;j++){
			$('#grid-container').append('<div class="number-cell" id="number-cell-'+i+'-'+j+'"></div>');
			$('#grid-container .number-cell').css('border-radius',cellwidth*0.1);
			$('#grid-container .number-cell').css('font-size',cellwidth*0.5);
			$('#grid-container .number-cell').css('line-height',cellwidth+'px');
			var numberCell = $('#number-cell-'+i+'-'+j);
			if(nums[i][j] == 0){
				numberCell.css('width','0px');
				numberCell.css('height','0px');
				numberCell.css('top',getPosTop(i,j)+cellwidth*0.5);
				numberCell.css('left',getPosLeft(i,j)+cellwidth*0.5);
			}else{
				numberCell.css('width',cellwidth);
				numberCell.css('height',cellwidth);
				numberCell.css('top',getPosTop(i,j));
				numberCell.css('left',getPosLeft(i,j));
				numberCell.css('background-color',getNumberBackgroundColor(nums[i][j]));
				numberCell.css('color',getNumberColor(nums[i][j]));
				numberCell.text(nums[i][j]);
			}
			hasConflicted[i][j] = false;
		}
	}
}

//在随机的单元格中生成一个数字
//1.在空余的单元格中随机找一个
//2.随机产生一个2或4
function generateOneNumber(){
	//判断是否还有空间，如果没有则直接返回
	if(noSpace(nums)){
		return;
	}
	
	//随机一个位置
	var count = 0;
	var temp = new Array();
	for(var i=0;i<4;i++){
		for(var j=0;j<4;j++){
			if(nums[i][j] == 0){
				temp[count] = i * 4 + j;//取余
				count++;
			}
		}
	}
	var pos = Math.floor(Math.random()*count);
	var randX = Math.floor(temp[pos] / 4);
	var randY = Math.floor(temp[pos] % 4);
	
	//随机一个数字
	var randNumber = Math.random() < 0.5 ? 2 : 4;
	
	//显示数字
	nums[randX][randY] = randNumber;
	showNumberWithAnimation(randX,randY,randNumber);
}

//实现键盘的响应
$(document).keydown(function(event){
	event.preventDefault();
	switch(event.keyCode){
		case 37://left
			if(canMoveLeft(nums)){
				moveLeft();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
			break;
		case 38://up
			if(canMoveUp(nums)){
				moveUp();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
			break;
		case 39://right
			if(canMoveRight(nums)){
				moveRight();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
			break;
		case 40://down
			if(canMoveDown(nums)){
				moveDown();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
			break;
		default:
			break;
	}
});


//实现触摸滑动响应
document.addEventListener('touchstart',function(event){
	startx = event.touches[0].pageX;
	starty = event.touches[0].pageY;
});

document.addEventListener('touchend',function(event){
	endx = event.changedTouches[0].pageX;
	endy = event.changedTouches[0].pageY;
	
	//判断运动的方向
	var deltax = endx - startx;
	var deltay = endy - starty;
	
	//判断当滑动的距离小于一定的临界值时不做任何操作
	if(Math.abs(deltax) < documentwidth*0.1 && Math.abs(deltay) < documentwidth*0.1){
		return;
	}
	
	if(Math.abs(deltax) >= Math.abs(deltay)){//水平方向运动
		if(deltax>0){//向右运动
			if(canMoveRight(nums)){
				moveRight();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
		}else{//向左运动
			if(canMoveLeft(nums)){
				moveLeft();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
		}
	}else{//垂直方向运动
		if(deltay>0){//向下运动
			if(canMoveDown(nums)){
				moveDown();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
		}else{//向上运动
			if(canMoveUp(nums)){
				moveUp();
				setTimeout(generateOneNumber(),200);
				setTimeout(isGameover(),3000);
			}
		}
	}
});

/*
	向左移动 需要对每一个数字的左边进行判断，选择落脚点（2种情况）
		1.落脚点没有数字，并且移动路径中没有障碍物
		2.落脚点数字和自己相同，并且移动路径中没有障碍物
*/
function moveLeft(){
	for(var i=0;i<4;i++){
		for(var j=1;j<4;j++){
			if(nums[i][j] != 0){
				for(var k=0;k<j;k++){
					if(nums[i][k] == 0 && noBlockHorizontal(i,k,j,nums)){//第i行的第k-j列判断是否有障碍物
						//移动操作
						showMoveAnimation(i,j,i,k);
						nums[i][k] = nums[i][j];
						nums[i][j] = 0;
					}else if(nums[i][k] == nums[i][j] && noBlockHorizontal(i,k,j,nums) && !hasConflicted[i][k]){
						//进行数值的叠加
						showMoveAnimation(i,j,i,k);
						nums[i][k] += nums[i][j];
						nums[i][j] = 0;
						//统计分数
						score += nums[i][k];
						updateScore(score);
						hasConflicted[i][k] = true;
					}
					if(nums[i][k]==256)   	nums[i][k]=0;
				}
			}
		}
	}
	//更新页面上的数字单元格，此处才是真正的更新显示
	setTimeout(updateView,200);
}
function moveRight(){
	for(var i=0;i<4;i++){
		for(var j=2;j>=0;j--){
			if(nums[i][j] != 0){
				for(var k=3;k>j;k--){
					if(nums[i][k] == 0 && noBlockHorizontal(i,j,k,nums)){//第i行的第j-k列判断是否有障碍物
						showMoveAnimation(i,j,i,k);
						nums[i][k] = nums[i][j];
						nums[i][j] = 0;
					}else if(nums[i][k] == nums[i][j] && noBlockHorizontal(i,j,k,nums) && !hasConflicted[i][k]){
						showMoveAnimation(i,j,i,k);
						nums[i][k] += nums[i][j];
						nums[i][j] = 0;
						score += nums[i][k];
						updateScore(score);
						hasConflicted[i][k] = true;
					}
					if(nums[i][k]==256)		nums[i][k]=0;
				}
			}
		}
	}
	setTimeout(updateView,200);
}
function moveUp(){
	for(var j=0;j<4;j++){
		for(var i=1;i<4;i++){
			if(nums[i][j] != 0){
				for(var k=0;k<i;k++){
					if(nums[k][j] == 0 && noBlockVertical(j,k,i,nums)){//第j列的第k-i行是否有障碍物
						showMoveAnimation(i,j,k,j);
						nums[k][j] = nums[i][j];
						nums[i][j] = 0;
					}else if(nums[k][j] == nums[i][j] && noBlockVertical(j,k,i,nums) && !hasConflicted[k][j]){
						showMoveAnimation(i,j,k,j);
						nums[k][j] += nums[i][j];
						nums[i][j] = 0;
						score += nums[k][j];
						updateScore(score);
						hasConflicted[k][j] = true;
					}
					if(nums[k][j]==256)		nums[k][j]=0;
				}
			}
		}
	}
	setTimeout(updateView,200);
}
function moveDown(){
	for(var i=2;i>=0;i--){
		for(var j=0;j<4;j++){
			if(nums[i][j] != 0){
				for(var k=3;k>i;k--){
					if(nums[k][j] == 0 && noBlockVertical(j,i,k,nums)){//第j列的第i-k行是否有障碍物
						showMoveAnimation(i,j,k,j);
						nums[k][j] = nums[i][j];
						nums[i][j] = 0;
					}else if(nums[k][j] == nums[i][j] && noBlockVertical(j,i,k,nums) && !hasConflicted[k][j]){
						showMoveAnimation(i,j,k,j);
						nums[k][j] += nums[i][j];
						nums[i][j] = 0;
						score += nums[k][j];
						updateScore(score);
						hasConflicted[k][j] = true;
					}
					if(nums[k][j]==256)		nums[k][j]=0;
				}
			}
		}
	}
	setTimeout(updateView,200);
}